package net.yrom.screenrecorder;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.media.projection.MediaProjection;
import android.media.projection.MediaProjectionManager;
import android.os.Build;
import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;

import com.stardust.util.IntentExtras;

import net.yrom.screenrecorder.core.RecordConfig;
import net.yrom.screenrecorder.rtmp.RESFlvData;
import net.yrom.screenrecorder.rtmp.RESFlvDataCollecter;
import net.yrom.screenrecorder.task.RtmpStreamingSender;
import net.yrom.screenrecorder.task.ScreenRecorder;

import org.autojs.autojs.autojs.AutoJs;

import java.lang.ref.WeakReference;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public class ScreenRecordActivity extends Activity {


    //    private ScreenRecorder screenRecorder;
//    private RtmpStreamingSender rtmpStreamingSender;
//    private ExecutorService executorService;
    private RecordConfig recordConfig;
    //    private MediaProjectionManager mediaProjectionManager;
//    private MediaProjection mediaProjection;
//    private Intent data;
    private static ScreenPush instance;

    public static synchronized void start(Context ctx, RecordConfig recordConfig) {
//        if (instance != null) {
//            stop();
//        }
//        Intent intent = new Intent(ctx, ScreenRecordActivity.class)
//                .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//        IntentExtras.newExtras()
//                .put("recordConfig", recordConfig)
//                .putInIntent(intent);
//        ctx.startActivity(intent);
        if (instance == null) {
            AutoJs.getInstance().getGlobalConsole().log("未发现推流实例,开始创建");
            Intent intent = new Intent(ctx, ScreenRecordActivity.class)
                    .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            IntentExtras.newExtras()
                    .put("recordConfig", recordConfig)
                    .putInIntent(intent);
            ctx.startActivity(intent);
        } else {
            AutoJs.getInstance().getGlobalConsole().log("推流实例已存在");
            instance.recordConfig = recordConfig;
            instance.startRecord();
        }
    }

    public synchronized static void stop() {
//        if (instance != null) {
//            AutoJs.getInstance().getGlobalConsole().log("停止推流和关闭");
//            instance.stopCapture();
//            instance.finish();
//            instance = null;
//        }
        if (instance != null) {
            AutoJs.getInstance().getGlobalConsole().log("停止推流");
            instance.stopCapture();
        }
    }

    private static class ScreenPush {
        private ScreenRecorder screenRecorder;
        private RtmpStreamingSender rtmpStreamingSender;
        private ExecutorService executorService;
        private RecordConfig recordConfig;
        private final MediaProjectionManager mediaProjectionManager;
        private MediaProjection mediaProjection;
        private final Intent data;
        private final AtomicBoolean record;


        public ScreenPush(RecordConfig recordConfig, MediaProjectionManager mediaProjectionManager, Intent data) {
            this.recordConfig = recordConfig;
            this.mediaProjectionManager = mediaProjectionManager;
            this.data = data;
            this.record = new AtomicBoolean(false);
        }

        private synchronized void startRecord() {
            if (record.get()) {
                stopCapture();
            }
            if (recordConfig != null) {
                mediaProjection = mediaProjectionManager.getMediaProjection(Activity.RESULT_OK, data);
                if (mediaProjection != null) {
                    rtmpStreamingSender = new RtmpStreamingSender(recordConfig.getRtmpUrl());
                    rtmpStreamingSender.sendStart();
                    RESFlvDataCollecter collecter = (flvData, type) -> rtmpStreamingSender.sendFood(flvData, type);
                    screenRecorder = new ScreenRecorder(collecter, recordConfig.getWidth(), recordConfig.getHeight(), recordConfig.getBitrate(), recordConfig.getDpi(), mediaProjection);
                    this.executorService = new ThreadPoolExecutor(3, 3, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<>(1));
                    executorService.execute(rtmpStreamingSender);
                    executorService.execute(screenRecorder);
                    AutoJs.getInstance().getGlobalConsole().log("开始推流");
                    record.set(true);
                } else {
                    AutoJs.getInstance().getGlobalConsole().log("未获取到权限");
                    stopCapture();
                    instance = null;
                }
            }
        }


        private void stopCapture() {
            record.set(false);
            // 执行停止捕获屏幕的逻辑
            if (screenRecorder != null) {
                screenRecorder.quit();
                screenRecorder = null;
            }
            if (rtmpStreamingSender != null) {
                rtmpStreamingSender.sendStop();
                rtmpStreamingSender.quit();
                rtmpStreamingSender = null;
            }
            if (mediaProjection != null) {
                mediaProjection.stop();
            }
            if (executorService != null) {
                executorService.shutdown();
                executorService = null;
            }
        }
    }


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (instance != null) {
            return;
        }
        IntentExtras extras = IntentExtras.fromIntentAndRelease(getIntent());
        this.recordConfig = extras.get("recordConfig");
        AutoJs.getInstance().getGlobalConsole().log("创建activity成功");
        MediaProjectionManager mediaProjectionManager = (MediaProjectionManager) getSystemService(MEDIA_PROJECTION_SERVICE);
        Intent screenCaptureIntent = mediaProjectionManager.createScreenCaptureIntent();
        startActivityForResult(screenCaptureIntent, 1000);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        MediaProjectionManager mediaProjectionManager = (MediaProjectionManager) getSystemService(MEDIA_PROJECTION_SERVICE);
//        MediaProjection mediaProjection = mediaProjectionManager.getMediaProjection(resultCode, data);
//        if (mediaProjection != null) {
//            if (recordConfig != null) {
//                rtmpStreamingSender = new RtmpStreamingSender(recordConfig.getRtmpUrl());
//                rtmpStreamingSender.sendStart();
//                RESFlvDataCollecter collecter = (flvData, type) -> rtmpStreamingSender.sendFood(flvData, type);
//                screenRecorder = new ScreenRecorder(collecter, recordConfig.getWidth(), recordConfig.getHeight(), recordConfig.getBitrate(), recordConfig.getDpi(), mediaProjection);
//                executorService.execute(rtmpStreamingSender);
//                executorService.execute(screenRecorder);
//                AutoJs.getInstance().getGlobalConsole().log("开始推流");
//            }
//        }

        if (instance == null) {
            instance = new ScreenPush(recordConfig, mediaProjectionManager, data);
            instance.startRecord();
        }
        finish();
    }
}
